<template>
  <div>
    <van-search
        v-model="SearchText"
        placeholder="请输入搜索关键词"
        show-action
        @search="onSearch"
        @cancel="onCancel"
        style="position:fixed;z-index:1;width:100%"
      />
    <van-row type="flex">
      <van-col style="margin-top:44px;">
        <van-badge-group :active-key="activeKey" style="overflow: scroll; border-right: solid 2px #fafafa;" v-bind:style="{height: mainHeight+'px'}">
          <van-badge v-for="(e, index) in categorys" v-bind:key="index" :title="e.typeName" @click="chooseCategory(index, e.typeId)" />
        </van-badge-group>
      </van-col>
      <van-col style="width:100%;margin-top:44px;">
        <van-cell-group style="overflow: scroll" v-bind:style="{height: mainHeight+'px'}">
          <van-cell v-for="(e, index) in dishes_show" v-bind:key="index" :title="e.productName" :value="e.productId" :label="e.productSpell" @click="chooseDish(e)"/>
        </van-cell-group>
      </van-col>
    </van-row>
    <!-- 悬浮按钮 -->
    <van-button @click.native="showPlan" tag="div" type="primary" style="border-radius:50%; position: absolute;bottom:110px;right:20px;">
      <div v-if="dishes_choose.length" class="van-info van-badge__info" style="z-index:100">{{ dishes_choose.length }}</div>
      <van-icon name="shopping-cart" />
    </van-button>
    <van-button @click.native="showNeed" tag="div" type="primary" style="border-radius:50%; position: absolute;bottom:60px;right:20px;" plain>
      <div v-if="needs.length" class="van-info van-badge__info" style="z-index:100">{{ needs.length }}</div>
      <van-icon name="pending-orders" />
    </van-button>
    <!-- 购物车 -->
    <van-popup v-model="show2" position="right" style="width:80%">
      <div style="width: 100%;overflow: scroll;" v-bind:style="{height: mainHeight + 44 + 'px'}">
        <van-cell-group>
          <van-cell v-for="(e, index) in dishes_choose" v-bind:key="index" :title="e.productName" :label="e.productId">
            <!-- <van-stepper v-if="show3" v-model="e.planAmount" min="0" @change="ifDel(e, index)" /> -->
            <van-button type="small" @click="chooseDish(e)">{{e.planAmount}}</van-button>
          </van-cell>
        </van-cell-group>
      </div>
      <van-button :disabled="dishes.length === 0" style="position: absolute; bottom: 0px;left: 0px;" type="primary" size="large" @click="generateBill">生成用料单</van-button>
    </van-popup>
    <!-- 物料清单 -->
    <van-popup v-model="show4" position="right" style="width:100%">
      <van-nav-bar
        title="物料清单"
        left-text="返回"
        left-arrow
        @click-left="show4 = false"
      />
      <div style="width: 100%;overflow: scroll;" v-bind:style="{height: mainHeight + 44 + 'px'}">
        <van-cell-group>
          <van-cell v-for="(e, index) in needs" v-bind:key="index" :title="e.bomName" :label="e.bomTypeName + ' 总计用料量:' + e.calAmount">
            <!-- <van-stepper v-if="show3" v-model="e.planAmount" min="0" @change="ifDel(e, index)" /> -->
            <van-button type="small" @click="chooseNeed(e)">{{e.applyAmount + e.bomUnit}}</van-button>
          </van-cell>
        </van-cell-group>
      </div>
      <van-button :disabled="needs.length === 0" style="position: absolute; bottom: 0px;left: 0px;" type="primary" size="large" @click="submit">提交</van-button>
    </van-popup>
    <!-- 数值选择 -->
    <van-dialog v-model="show1" show-cancel-button :before-close="beforeClose">
      <van-stepper v-model="planAmount"/>
    </van-dialog>
    <van-dialog v-model="show3" show-cancel-button :before-close="beforeClose2">
      <van-stepper min=0 v-model="planAmount"/>
    </van-dialog>
    <van-dialog v-model="show5" show-cancel-button :before-close="beforeClose3">
      <van-stepper min=0 v-model="applyAmount"/>
    </van-dialog>
    <router-view />
  </div>
</template>

<script>
import request from '@/utils/request';

export default {
  data() {
    return {
      activeKey: 0,
      SearchText: '',
      mainHeight: 0,
      categorys: [], // 分类
      category_dishes: [], // 分类好的菜单
      dishes: [], // 所有菜单
      dishes_show: [], // 正在展示的菜单
      dishes_choose: [], // 选中的菜单
      dish_choose: {}, // 选中的菜单
      needs: [], // 物料清单
      need_choose: {},
      options: [],
      categoryIndex: 0, // 分类索引
      show1: false, // 控制选取数量的对话框
      show2: false, // 控制购物车
      show3: false, // 控制购物车数量
      show4: false, // 控制物料清单
      show5: false, // 控制物料数量
      planAmount: 1, // 菜品数量
      applyAmount: 1, // 物料申请调整数量
    }
  },
  methods: {
    onClick(key) {
      this.activeKey = key;
    },
    onSearch(text) {
      if (text) {
        this.dishes_show = this.dishes.filter(e=>e.productId.startsWith(text) || e.productSpell.startsWith(text.toUpperCase()) || e.productName.startsWith(text));
      } else {
        this.dishes_show = this.category_dishes[this.categorys[this.activeKey].typeId];
      }
    },
    showPlan() {
      this.show2 = true;
    },
    showNeed() {
      this.show4 = true;
    },
    onCancel() {
      this.dishes_show = this.category_dishes[this.categorys[this.activeKey].typeId];
    },
    chooseCategory(index, typeId) {
      this.activeKey = index;
      this.dishes_show = this.category_dishes[typeId];
    },
    chooseDish(dish) {
      if (dish.planAmount) {
        this.planAmount = dish.planAmount;
        this.show3 = true;
      } else {
        this.planAmount = 1;
        this.show1 = true;
      }
      this.dish_choose = dish;
    },
    chooseNeed(m) {
      this.show5 = true;
      this.applyAmount = m.applyAmount;
      this.need_choose = m;
    },
    updateAmount(productId, planAmount) {
      return request({
        url: '/productPlan/updateAmount',
        method: 'post',
        data: {
          productId: productId,
          planAmount: planAmount
        }
      })
    },
    // 添加进购物车前
    beforeClose(action, done) {
      if (action === 'confirm') {
        this.dishes_choose.forEach(e => {
          if (e.productId == this.dish_choose.productId) {
            this.updateAmount(e.productId, e.planAmount + this.dishes_choose.planAmount).then(res => {
              if (res.data.result === 'success') {
                e.planAmount += this.dish_choose.planAmount;
                done();
              } else {
                alert('错误');
              }
            });
            reutrn;
          }
        })
        request({
          url: '/productPlan/insertFromProductInfo',
          method: 'post',
          data: {
            productId: this.dish_choose.productId,
            planAmount: this.planAmount
          }
        }).then(res => {
          let data = res.data;
          if (data.result === 'success') {
            this.dishes_choose.push({
              productId: this.dish_choose.productId,
              productName: this.dish_choose.productName,
              productSpell: this.dish_choose.productSpell,
              planAmount: this.planAmount,
              serialNo: data.msg
            });
            done();
          }
        });
      } else {
        done();
      }
    },
    // 在购物车里编辑
    beforeClose2(action, done) {
      if (action === 'confirm') {
        if (this.planAmount === 0) {
          request({
            url: `/productPlan/deleteByPrimaryKey/${this.dish_choose.serialNo}`,
            method: 'get'
          }).then(res => {
            done();
            if (res.data.result === 'success') {
              this.dishes_choose = this.dishes_choose.filter(e => {
                return e.productId !== this.dish_choose.productId;
              })
            } else {
              alert('错误');
            }
          });
        } else {
          this.updateAmount(this.dish_choose.productId, this.planAmount).then(res => {
            done();
            if (res.data.result === 'success') {
              this.dishes_choose.forEach(e => {
                if (e.productId === this.dish_choose.productId) {
                  e.planAmount = this.planAmount;
                }
              })
            } else {
              alert('错误');
            }
          });
        }
      } else {
        done();
      }
    },
    // 物料清单里编辑
    beforeClose3(action, done) {
      if (action === 'confirm') {
        request({
          url: '/bill/updateNeed',
          method: 'post',
          data: {
            serialNo: this.need_choose.serialNo,
            applyAmount: this.applyAmount
          }
        }).then(res => {
          if (res.data.result === 'success') {
            done();
            this.need_choose.applyAmount = this.applyAmount;
          }
        })
      }
    },
    generateBill() {
      this.$dialog.confirm({
        message: '是否确认生成用料清单',
        beforeClose: (action, done) => {
          if (action == 'confirm') {
            request({
              url: '/bill/generate',
              method: 'get'
            }).then(res => {
              if (res.data.result === 'success') {
                this.getNeeds().then(() => {
                  this.show4 = true;
                  done();
                });
              }
            })
          } else {
            done();
          }
        }
      })
    },
    submit() {
      this.$dialog.confirm({
        message: '确认提交?'
      }).then(() => {
        request({
          url: '/bill/submit',
          method: 'get'
        }).then(res => {
          if (res.data.result === 'success') {
            this.dishes_choose = [];
            this.needs = [];
            this.show4 = false;
          }
        });
      }).catch(() => {
      })
    },
    // 物料清单
    getNeeds() {
      return new Promise(resolve => {
        request({
          url: '/bill/selectNeeds',
          method: 'get'
        }).then(res => {
          let data = res.data;
          if (data.result === 'success') {
            this.needs = data.needs;
            resolve();
          }
        })
      });
    }
    // back() {
    //   this.show4 = false;
    // }
    /*
    ifDel(e, index) {
      if (e.planAmount === 0) {
        this.$dialog.confirm({
          message: '是否删除', 
          beforeClose:(action, done) => {
            if (action === 'confirm') {
              request({
                url: `/productPlan/deleteByPrimaryKey/${e.productId}`,
                methods: 'get'
              }).then(res => {
                done();
                if (res.data.result === 'success') {
                  this.dishes_choose.splice(index, index + 1);
                } else {
                  alert('错误');
                }
              });
            } else {
              this.dishes_choose[index].planAmount = 1;
              done();
            }
          }
        });
      }
    }
    */
  },
  mounted() {
    // this.$toast.loading({
    //   duration: 0,
    //   mask: true,
    //   forbidClick: true,
    //   message: '加载中...'
    // });
    // 菜单
    request({
      url: '/productInfo/selectAll',
      method: 'get',
    }).then(res => {
      const data = res.data;
      if (data.result === 'success') {
        this.dishes = data.productInfoList;
        this.dishes.forEach(e => {
          if (this.category_dishes[e.typeId]) {
            this.category_dishes[e.typeId].push(e);
          } else {
            this.categorys.push({
              typeName: e.typeName,
              typeId: e.typeId
            });
            this.category_dishes[e.typeId] = [e];
          }
        });
        this.dishes_show = this.category_dishes[this.categorys[0].typeId];
        // 缓存
        // this.$store.dispatch('SetDishes', {
        //   categorys: this.categorys, // 分类
        //   category_dishes: this.category_dishes, // 分类好的菜单
        //   dishes: this.dishes, // 所有菜单
        // }).then(() => {
        //   console.log(1);
        // });
      }
      // this.$toast.clear();
    });
    // 购物车
    request({
      url: `/productPlan/selectByInputUser`,
      method: 'get'
    }).then(res => {
      let data = res.data;
      if (data.result === 'success') {
        this.dishes_choose = data.productPlanList;
      }
    });
    this.getNeeds();
    this.mainHeight = window.innerHeight - 44 - 50;
    // for (let i = 0; i < 20; i++) {
    //   let dishes = [];
    //   for (let j = 0; j < 20; j++) {
    //     dishes.push({name: `品类${i+ 1}菜肴${j + 1}`});
    //   }
    //   this.allData.push({
    //     category: `品类${i + 1}`,
    //     value: dishes
    //   });
    // }
    // this.dishes = this.allData[0]['value'];
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.van-popup--right {
  height: 100%;
}
</style>
